package com.wangyan.javabean2doc;

import javax.swing.*;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

/**
 * @author wangyan
 * @date 2024/01/30/9:04
 * @description
 */
public class ExcelAdapter implements ActionListener {
    private Clipboard system;
    private StringSelection stsel;
    private JTable jTable1;

    /**
     * Excel 适配器由 JTable 构成，
     * 它实现了 JTable 上的复制粘贴
     * 功能，并充当剪贴板监听程序。
     */
    public ExcelAdapter(JTable myJTable) {
        jTable1 = myJTable;
        KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK, false);
        jTable1.registerKeyboardAction(this, "Copy", copy, JComponent.WHEN_FOCUSED);
        system = Toolkit.getDefaultToolkit().getSystemClipboard();
    }

    /**
     * 此适配器运行图表的公共读方法。
     */
    public JTable getJTable() {
        return jTable1;
    }

    public void setJTable(JTable jTable1) {
        this.jTable1 = jTable1;
    }

    /**
     * 在我们监听此实现的按键上激活这种方法。
     * 此处，它监听复制和粘贴 ActionCommands。
     * 包含不相邻单元格的选择导致选择无效，
     * 而且此后复制动作无法执行。
     * 粘贴的方法是将选定内容的左上角与
     * JTable 的当前选定内容的第一个元素对齐。
     */
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().compareTo("Copy") == 0) {
            // 检查以确保我们仅选择了单元格的相邻块
            int numcols = jTable1.getSelectedColumnCount();
            int numrows = jTable1.getSelectedRowCount();
            int[] rowsselected = jTable1.getSelectedRows();
            int[] colsselected = jTable1.getSelectedColumns();
            if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0] &&
                    numrows == rowsselected.length) &&
                    (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0] &&
                            numcols == colsselected.length))) {
                JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
                        "Invalid Copy Selection",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }
            copy(numcols, numrows, rowsselected, colsselected, null);

        }

    }

    public void copy(int numcols, int numrows, int[] rowsselected, int[] colsselected, String tableHeader) {

        // 构建 HTML 表格的字符串表示
        StringBuilder html = new StringBuilder();
        html.append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">\n" +
                "<head>\n" +
                "<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\n" +
                "<meta name=Generator content=\"Microsoft Excel\">\n" +
                "</head>\n" +
                "<body>\n" +
                "<!--StartFragment-->\n" +
                "<table style=\"width: 540px;\">");

        for (int i = 0; i < numrows; i++) {
            html.append("<tr>");
            for (int j = 0; j < numcols; j++) {
                String valueAt = jTable1.getValueAt(rowsselected[i], colsselected[j]).toString();

                html.append("<td>").append(valueAt).append("</td>");
/*                if(valueAt.contains("\n")||valueAt.contains("\t")){
                    valueAt = "\""+valueAt+"\"";
                }
                sbf.append(valueAt);
                if (j < numcols - 1) sbf.append("\t");*/
            }
            //sbf.append("\n");
            html.append("</tr>");
        }
        html.append("</table>\n" +
                "<!--EndFragment-->\n" +
                "</body>\n" +
                "</html>");
        system.setContents(new HtmlTransferable(html.toString()), null);
    }

    public void generateHtmlTable() {

        // 获取表格的模型
        TableModel model = jTable1.getModel();

        // 构建 HTML 表格的字符串表示
        StringBuilder html = new StringBuilder();
        html.append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">\n" +
                "<head>\n" +
                "<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\n" +
                "<meta name=Generator content=\"Microsoft Excel\">\n" +
                "</head>\n" +
                "<body>\n" +
                "<!--StartFragment-->\n" +
                "<table style=\"width: 540px;\">");

        // 表头
        html.append("<tr style=\"background: #B4C6E7;\">");
        for (int col = 0; col < model.getColumnCount(); col++) {
            html.append("<th style=\"width: 20%;\">").append(jTable1.getColumnName(col)).append("</th>");
        }
        html.append("</tr>");

        for (int row = 0; row < model.getRowCount(); row++) {
            html.append("<tr>");
            for (int col = 0; col < model.getColumnCount(); col++) {
                html.append("<td>").append(model.getValueAt(row, col)).append("</td>");
            }
            html.append("</tr>");
        }
        html.append("</table>\n" +
                "<!--EndFragment-->\n" +
                "</body>\n" +
                "</html>");

        // 将 HTML 字符串放入剪贴板
        system.setContents(new HtmlTransferable(html.toString()),null);
    }

}
